//
//  CollectionSection.swift
//  Risac
//
//  Created by remy on 2018/8/8.
//

import UIKit

open class CollectionSectionItem: NSObject {
    public var model: Any?
    public var indexPath: IndexPath?
    public var cellItems: [CollectionCellItem] = []
    public var showCellItems: Bool = true
    public var sectionInset: UIEdgeInsets = .zero
    public var lineSpacing: CGFloat = 0.0
    public var itemSpacing: CGFloat = 0.0
    // UICollectionViewFlowLayout布局生效
    public fileprivate(set) weak var sectionHeader: CollectionSection?
    public fileprivate(set) weak var sectionFooter: CollectionSection?
    public var sectionHeaderClass: CollectionSection.Type?
    public var sectionFooterClass: CollectionSection.Type?
    public var sectionHeaderHeight: CGFloat?
    public var sectionFooterHeight: CGFloat?
    public lazy var sectionHeaderReuseIDSuffix: String = ""
    public lazy var sectionFooterReuseIDSuffix: String = ""
    // CollectionFlexLayout,CollectionFlowLayout布局生效
    public fileprivate(set) weak var sectionStage: CollectionSection?
    public var sectionStageClass: CollectionSection.Type?
    public lazy var sectionMargin: UIEdgeInsets = .zero
    public lazy var sectionSpacing: CGFloat = 0.0
    public lazy var sectionStageReuseIDSuffix: String = ""
    // CollectionFlowLayout布局生效
    public lazy var flowCount: Int = 1
    open func reload() {}
}

open class CollectionSection: UICollectionReusableView {
    public var sectionItem: CollectionSectionItem? {
        didSet {
            if let item = sectionItem {
                if self.metaTypeName == item.sectionHeaderClass?.metaTypeName {
                    item.sectionHeader = self
                } else if self.metaTypeName == item.sectionFooterClass?.metaTypeName {
                    item.sectionFooter = self
                } else if self.metaTypeName == item.sectionStageClass?.metaTypeName {
                    item.sectionStage = self
                }
            }
            if let item = oldValue {
                if item.sectionHeader == self {
                    item.sectionHeader = nil
                } else if item.sectionFooter == self {
                    item.sectionFooter = nil
                } else if item.sectionStage == self {
                    item.sectionStage = nil
                }
            }
        }
    }
    
    func updateBinding(sectionItem: CollectionSectionItem?) {
        self.sectionItem = sectionItem
        UIView.performWithoutAnimation {
            updateSection(sectionItem: sectionItem)
        }
    }
    
    open func updateSection(sectionItem: CollectionSectionItem?) {}
    
    open override func prepareForReuse() {
        self.sectionItem = nil
        super.prepareForReuse()
    }
}
